<?php
namespace app\index\controller;

use think\Request;

class Order extends Common{
	
	//我的订单列表,代理订单
	public function index(){
		
		$status = Request::instance()->param('status');
		$key = Request::instance()->param('key','');
		$page = Request::instance()->param('page',1,'intval');
		
		if(!\RegexHelper::is_ids($status)){
			$status = -1;
		}
		$param = [
			'agentid' => AGENT_ID,
			'status' => $status,
			'key' => $key,
			'page' => $page,
		];
		
		$response = \ServerHelper::post('order_list',$param);
		$data = $this->J($response);

		return view('index',$data['data']);
	}

	
	//加载一个分页的数据
	public function order_loadpage(){
		$status = Request::instance()->param('status');
		$key = Request::instance()->param('key','');
		$page = Request::instance()->param('page',1,'intval');
		
		if(!\RegexHelper::is_ids($status)){
			$status = -1;
		}
		
		$param = [
			'agentid' => AGENT_ID,
			'status' => $status,
			'key' => $key,
			'page' => $page,
		];
		$response = \ServerHelper::post('order_list',$param);
		$data = $this->J($response);
		
		$info = $data['data'];
		
		$list = [];
		foreach($info['orderinfo'] as $k=>$v){
			$one = $v;
			$one['Status'] = __order_status($v['Status']);
			$one['buttons'] = __order_status_btns($v['Status']);
			$list[] = $one;
		}
		
		$data = [
			'list' => $list,//$info['orderinfo'],
			'status' => $info['search']['status'],
			'key' => $info['search']['key'],
			'page' => $info['search']['page'],
		];

		ajax('success',true,$data);
	}
	
	//本人订单详情
	public function detail(){
		$orderid = Request::instance()->param('id');
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => $orderid
		];
		$response = \ServerHelper::post('order_detail',$param);
		$data = $this->J($response);
		return view('',['data'=>$data['data']]);
	}
	
	//价差，查看下级订单详情
	public function jcdetail(){
		/*
		另外，价差的订单详情的接口
		/api/order/jcdetail.tsl
		参数：
		   agentId
		   orderId
		返回：
		   和以前order/detail.tsl的返回一样，只是把seller的数据去掉了
		*/
		$orderid = Request::instance()->param('id');
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => $orderid
		];
		$response = \ServerHelper::post('^/order/jcdetail',$param);
		$data = $this->J($response);
		if(empty($data['flag'])){
			$this->error($data['msg']);
		}
		return view('',['data'=>$data['data']]);
	}
	
	//已下的订单，查看打款凭证
	public function checkrep(){
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => Request::instance()->param('orderid')
		];
		$response = \ServerHelper::post('order_checkrep',$param);
		$data = $this->J($response);
		return view('',$data['data']);
	}
	
	//物流轨迹信息
	public function logistics(){
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => Request::instance()->param('orderid')
		];
		$response = \ServerHelper::post('order_wuliu',$param);
		$data = json_decode($response,true);
		if(!isset($data['flag'])){
			return view('',['data'=>'']);//$this->error('页面不存在');
		}
		if($data['flag'] == '0'){
			return view('',['data'=>'']);//$this->error('信息不存在');
		}
		
		return view('',['data'=>$data['data']]);
	}
	
	//确认收货
	public function receipt(){
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => Request::instance()->param('orderid')
		];
		$response = \ServerHelper::post('order_queren',$param);
		$data = $this->J($response);
		if(!empty($data['flag'])){
			ajax('操作成功',true);
		}
		ajax('确认失败');
	}
	
	//申请撤单
	public function applycancel(){
		$request = Request::instance();
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => $request->param('orderid')
		];
		
		if($request->isPost()){
			$response = \ServerHelper::post('order_cancelsubmit',$param);
			$data = $this->J($response);
			if(empty($data['flag'])){
				ajax('撤销失败');
			}else{
				ajax('撤销成功',true);
			}
			
		}else{
			$response = \ServerHelper::post('order_applycancel',$param);
			$data = $this->J($response);
			//var_dump($data);
			
			return view('',['data'=>$data['data']]);
		}
	}
	
	//直接取消订单
	public function cancel(){
		$request = Request::instance();
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => $request->param('orderid')
		];
		$response = \ServerHelper::post('order_cancel',$param);

		$data = $this->J($response);
		if(empty($data['flag'])){
			ajax('取消失败');
		}else{
			ajax('取消成功',true);
		}
	}

	//购物车首页
    public function cart(){
		$result = \ServerHelper::post('cart_index',['agentid'=>AGENT_ID]);
		$data = $this->J($result);
		return view('',[
			'data' => $data['data']
		]);
    }
	
	//加购物车
	public function cart_add(){
		
		// /api/addproduct.tsl?agentid=AG_000001&products=[{"productid":"34621","buynum":0}]
		// 这个可以删除购物车
		
		$goods_str = Request::instance()->param('goods_id');
		$amount_str = Request::instance()->param('amount');
		
		if(!\RegexHelper::is_ids($goods_str) || !\RegexHelper::is_ids($amount_str)){
			ajax('参数错误',false,0);
		}
		
		$goods_arr = explode(',',$goods_str);
		$amount_arr = explode(',',$amount_str);
		$goods_arr = array_unique($goods_arr); //ID可以，数量不能去重
		
		if(count($goods_arr) != count($amount_arr)){
			ajax('参数错误',false,0);
		}
		
		$products = [];
		for($i=0;$i<count($goods_arr);$i++){
			$products[] = [
				'productid' => "{$goods_arr[$i]}",
				'buynum' => (int)$amount_arr[$i]
			];
		}
		
		$postData = [
			'agentid'=>AGENT_ID,
			'products'=> json_encode($products)
		];
		
		$result = \ServerHelper::post('cart_add',$postData);
		
		$data = $this->J($result);
		
		if($data['flag']){
			ajax('SUCCESS',true,[
				'list'=>$data['data'],
				'total_price'=>$data['orderamount'],
				'total_amount'=>$data['producttotalnum'],
			]);
		}else{
			ajax($data['msg'],false,[
				'list'=> empty($data['data']) ? [] : $data['data'],
				'total_price'=> empty($data['orderamount']) ? 0 : $data['orderamount'],
				'total_amount'=> empty($data['producttotalnum']) ? 0 : $data['producttotalnum'],
			]);
		}
	}
	
	//我下单订单确认
	public function confirm(){
		
		//接收ID
		$goods_str = Request::instance()->param('goods_id','',REG_IDS);
		$amount_str = Request::instance()->param('amount','',REG_IDS);
		
		if(!\RegexHelper::is_ids($goods_str) || !\RegexHelper::is_ids($amount_str)){
			ajax('参数错误',false,0);
		}
		
		$goods_arr = explode(',',$goods_str);
		$amount_arr = explode(',',$amount_str);
		$goods_arr = array_unique($goods_arr); //ID可以，数量不能去重
		
		if(count($goods_arr) != count($amount_arr)){
			$this->error('参数错误');
		}
		
		$products = [];
		for($i=0;$i<count($goods_arr);$i++){
			$products[] = [
				'productid' => (int)$goods_arr[$i],
				'buynum' => (int)$amount_arr[$i]
			];
		}
		
		$postData = [
			'agentid'=>AGENT_ID,
			'products'=> json_encode($products)
		];
		
		//发送ID，得到商品
		$result = \ServerHelper::post('orderconfirm',$postData);

		$data = $this->J($result);
		
		if(empty($data['flag'])){
			$this->error($data['msg']);
		}

		$express_list = []; //用于下拉
		$express_list_full = []; //用于切换后计算运费
		$express_default = ['id'=>'','value'=>'请选择','index'=>0];
		$_index = 0;
		
		//快递信息
		foreach($data['data']['express'] as $v){
			$express_list[] = ['id'=>$v['expressid'],'value'=>$v['expresscompany']];
			if($v['isdefault']){
				$express_default = [
					'id' => $v['expressid'],
					'value' => $v['expresscompany'],
					'expressprice' => $v['expressprice'],
					'index' => $_index //下拉绑定后显示哪个
				];
			}
			$express_list_full[$v['expressid']] = [
				'value' => $v['expresscompany'],
				'expressprice' => $v['expressprice']
			];
			$_index++;
		}
		
		$express = [
			'list' => json_encode($express_list,JSON_UNESCAPED_UNICODE),
			'listfull' => json_encode($express_list_full,JSON_UNESCAPED_UNICODE),
			'default' => $express_default
		];
		
		//得到前段需要的商品信息
		$products = [];
		foreach($data['data']['product'] as $v){
			$products[] = [
				'productid' => (int)$v['productid'],
				'buynum' => (int)$v['buynum'],
				'productprice' => (float)$v['productprice'],
				'productname' => $v['productname'],
			];
		}
		
		//地址列表
		$param = [
			'action' => 'list',
			'agentid' => AGENT_ID
		];
		$response = \ServerHelper::post('address',$param);
		$address_list = $this->J($response);
		if(!isset($address_list['data'])){
			$address_list['data'] = [];
		}
		
		return view('',[
			'data' => $data['data'],
			'products' => json_encode($products,JSON_UNESCAPED_UNICODE),
			'express' => $express,
			'address' => json_encode($address_list['data'],JSON_UNESCAPED_UNICODE)
		]);
	}
	
	//下单时修改地址，重新计算运费
	public function changeaddress(){
		$request = Request::instance();
		$postData = [
			'agentid' => AGENT_ID,
			'tsid' => $request->param('tsid'),
			'products' => $request->param('products','','urldecode')
		];
		$response = \ServerHelper::post('order_changeaddress',$postData);
		$response = json_decode($response,true);
		if(empty($response['flag']))
			ajax('运费获取失败');
		
		$list = [];
		$listfull = [];
		foreach($response['data'] as $k=>$v){
			$list[] = [
				'id' => $v['expressid'],
				'value' => $v['expresscompany'],
			];
			$listfull[$v['expressid']] = [
				'id' => $v['expressid'],
				'value' => $v['expresscompany'],
				'expressprice' => $v['expressprice'],
			];
		}
		
		ajax('运费获取成功',true,[
			'lunzi' => $list,
			'list' => $listfull
		]);
	}
	
	//正式下单
	public function add(){
		$data = Request::instance()->param('data','','trim');

		$json = json_decode($data,true);
		if(empty($json) || empty($json['address']))
			ajax('下单失败');
		
		$orderparam = $json;
		$orderparam['agentid'] = AGENT_ID;
		
		$postData = [
			'orderparam' => json_encode($orderparam)
		];
		
		$response = \ServerHelper::post('orderadd',$postData);
		$data = $this->J($response);
		
		if($data['flag'] == 1){
			ajax($data['msg'],true,$data['data']['orderid']);
		}else{
			ajax($data['msg'],false);
		}
	}
	
	//支付页面
	public function pay(){
		
		/*
3种支付流程
	线上支付()
	货款余额、现金余额  ：  直接支付，显示成功
	线下打款  https://fshn.weiyianws.com/offline/mine?id=4978600
	

2个支付步骤
	货款  
	付现金(运费+内购)


4个支付选项
	线上支付
	货款余额
	现金余额
	线下打款

		*/
		
		//D20200412214133E7C8D43D
		$orderid = Request::instance()->param('orderid');
		if($orderid == ''){
			abort(404,'页面不存在');
		}
		
		$postData = [
			'agentid' => AGENT_ID,
			'orderid' => $orderid
		];
		
		$responst = \ServerHelper::post('pay_show',$postData);
		$data = $this->J($responst);
		
		if($data['flag'] == 0){
			abort(404,'页面不存在');
		}

		$steps_new = null;
		foreach($data['data']['steps'] as $k=>$o){
			if($o['status'] == 0){
				$steps_new = $o;
				break;
			}
		}
		
		if(empty($steps_new)){
			//(货款orderamount 现金cashmount)都成功了，则跳转到列表去
			//jia yige 2bu dou zhifu chenggong zhanshi yemian
			
			$this->redirect('Order/payresult',['orderid'=>$orderid]);
			
		}
		//去除已经支付了的步骤 且 仅保留当前要支付的步骤
		$data['data']['steps'] = $steps_new; 
		//附加订单ID
		$data['data']['orderid'] = $orderid;
		
		return view('',[
			'data' => $data['data']
		]);
	}
	
	//①余额支付
	public function blancepay(){
		
		//现金余额、货款余额
		$orderid = Request::instance()->param('orderid');
		$ordertype = Request::instance()->param('ordertype'); //订单类型(付哪一个步骤)
		$paytype = Request::instance()->param('paytype'); //支付类型
		$loginpwd = Request::instance()->param('loginpwd'); //登陆密码
		
		if($orderid == ''){
			ajax('订单号错误');
		}
		if($ordertype  == ''){
			ajax('参数错误');
		}
		if($paytype == ''){
			ajax('参数错误');
		}
		$pm = [
			'agentid' => AGENT_ID,
			'orderid' => $orderid,
			'ordertype' => $ordertype,
			'paytype' => $paytype,
			'loginpwd' => $loginpwd,
		];
		
		$response = \ServerHelper::post('balancepay',$pm);
		$data = $this->J($response);
		
		if($data['flag']){
			ajax('支付成功',true);
		}else{
			ajax($data['msg']);
		}
	}
	
	//②线下支付
	public function xxpay(){
		
		//现金余额、货款余额
		$orderid = Request::instance()->param('orderid');
		$ordertype = Request::instance()->param('ordertype'); //订单类型(付哪一个步骤)
		$paytype = Request::instance()->param('paytype'); //支付类型
		
		if($orderid == ''){
			$this->error('订单号错误');
		}
		if($ordertype  == ''){
			$this->error('参数错误');
		}
		if($paytype == ''){
			$this->error('参数错误');
		}
			
		if(Request::instance()->isPost()){
			
			$postdata = [
				'agentid' => AGENT_ID,
				'orderid' => $orderid,
				'ordertype' => $ordertype,
				'paytype' => $paytype,
				'repaccounttype' => Request::instance()->param('repaccounttype'),
				'repaccount' => Request::instance()->param('repaccount'),
				//'reppicture' => '', //打款凭证
				'remark' => Request::instance()->param('remark'),
			];
			$reppicture = Request::instance()->param('reppicture');
			if($postdata['repaccounttype'] == '' || $postdata['repaccount'] == ''){
				$this->error('请选择收款人账户');
			}
			$arr = explode(',',$reppicture);
			if(count($arr) < 1 || substr($arr[0],0,4) != 'http'){
				$this->error('请上传打款凭证');
			}
			$postdata['reppicture'] = json_encode($arr);

			$response = \ServerHelper::post('xxpay_do',$postdata);
			$response = $this->J($response);
			if($response['flag']){
				$this->redirect('Order/pay',['orderid'=>$orderid]);
			}else{
				$this->error($response['msg']);
			}
			
		}else{
		
			$request = [
				'agentid' => AGENT_ID,
				'orderid' => $orderid,
				'ordertype' => $ordertype,
				'paytype' => $paytype,
			];
			
			$response = \ServerHelper::post('xxpay',$request);
			$response = $this->J($response);
			if($response['flag'] == 0){
				$this->error($response['msg']);
			}
						
			//选择数据
			$accountType = [];
			$accountTypeFull = [];
			if(isset($response['data']['repaccount']['wechat'])){
				$accountType[] = [
					'id'=>$response['data']['repaccount']['wechat']['accountid'],
					'value'=>$response['data']['repaccount']['wechat']['accountname'],
				];
				$accountTypeFull['wechat'] = [
					'id'=>$response['data']['repaccount']['wechat']['accountid'],
					'value'=>$response['data']['repaccount']['wechat']['accountname'],
				];
			}
			if(isset($response['data']['repaccount']['alipay'])){
				$accountType[] = [
					'id'=>$response['data']['repaccount']['alipay']['accountid'],
					'value'=>$response['data']['repaccount']['alipay']['accountname'],
				];
				$accountTypeFull['alipay'] = [
					'id'=>$response['data']['repaccount']['alipay']['accountid'],
					'value'=>$response['data']['repaccount']['alipay']['accountname'],
				];
			}
			if(isset($response['data']['repaccount']['bank'])){
				$accountType[] = [
					'id'=>$response['data']['repaccount']['bank']['accountid'],
					'value'=>$response['data']['repaccount']['bank']['accountname'],
				];
				$accountTypeFull['bank'] = [
					'id'=>$response['data']['repaccount']['bank']['accountid'],
					'value'=>$response['data']['repaccount']['bank']['accountname'],
				];
			}
			
			return view('',[
				'data' => $response['data'],
				'ordertype' => $ordertype,
				'paytype' => $paytype,
				'orderid' => $orderid,
				'accounttype' => json_encode($accountType,JSON_UNESCAPED_UNICODE),
				'accounttypefull' => json_encode($accountTypeFull,JSON_UNESCAPED_UNICODE)
			]);
		}
	}
	
	
	//③微信支付
	public function wepay(){
		
		//现金余额、货款余额
		$orderid = Request::instance()->param('orderid');
		$ordertype = Request::instance()->param('ordertype'); //订单类型(付哪一个步骤)
		$paytype = Request::instance()->param('paytype'); //支付类型
		
		if($orderid == ''){
			$this->error('订单号错误');
		}
		if($ordertype  == ''){
			$this->error('参数错误');
		}
		if($paytype == ''){
			$this->error('参数错误');
		}
		
		//拉取支付信息
		$request = [
			'agentid' => AGENT_ID,
			'orderid' => $orderid,
			'ordertype' => $ordertype,
			'paytype' => $paytype,
		];
		$payinfo = \ServerHelper::post('wepay_show',$request);
		$payinfo = $this->J($payinfo);
		if($payinfo['flag'] != 1){ $this->error('支付发起失败'); }

		__log('orderid：'.$payinfo['data']['orderid'].'，payid：'.$payinfo['data']['payid'],'tmp' );
    
		$param = [
			'body' => $payinfo['data']['products'],
			'orderid' => $payinfo['data']['orderid'],
			'pay_no' => $payinfo['data']['payid'],
			'price' => intval($payinfo['data']['amount']), //价格(单位：分)
			'notify_url' => Request::instance()->domain() . url('Wepay/notify_url'),
		];

		$url = url('Wepay/index') . '?' . http_build_query($param);
    
		$this->redirect($url);
    
	}
	
	
	public function payresult(){
		$orderid = Request::instance()->param('orderid');
		$response = \ServerHelper::post('payresult',['agentid'=>AGENT_ID,'orderid'=>$orderid]);
		$data = $this->J($response);
		
		return view('',['data'=>$data['data']]);
	}
  
  
	//上传订单支付凭证、注册时的打款凭证
	public function img_upload(){
		#region 独立格式校验
		
		//var_dump($_FILES["image"]["name"]); exit;
		//ajax(json_encode($_FILES));
		
		if(!isset($_FILES["image"]["error"])){
			ajax('请选择图片');
		}
		if($_FILES["image"]["error"] == 1){
			ajax('图片尺寸过大');
		}else if($_FILES["image"]["error"] != 0){
			ajax('图片上传失败');
		}
		$extention = explode('.',$_FILES['image']['name']);
		$extention = end($extention);
		$allow = ['jpg','jpeg','pjpeg','gif','png'];
		if(!in_array(strtolower($extention),$allow)){
			ajax('文件格式不正确');
		}
		#endregion
		
		$ali = controller('Aliyun');
		$data = $ali->frontupload();
		
		$info = !empty($data['flag']) ? '上传成功' : '上传失败';
		
		ajax($info,$data['flag'],$data['data']);
		
	}
	
	//删除(未支付)订单临时支付凭证
	public function img_delete(){
		//登陆验证
		
		$picurl = Request::instance()->param('picurl');
		if(substr($picurl,0,4) != 'http'){
			ajax('删除失败');
		}
		
		//判断图片是否属于当前用户的订单的凭证
		$response = \ServerHelper::post('getorderinfowithpz',['picurl'=>base64_encode($picurl)]);
		$data = $this->J($response);
		if(!$data['flag'] || $data['data']['agentid'] != AGENT_ID){
			ajax('删除失败');
		}
		
		$host = config('server.api_host');
		$remotePath = str_replace($host,'',$picurl);
		
		$res = \ServerHelper::GetOSSConfig();
		$hp = new \AliyunOSSHelper($res);
		$data = $hp->DeleteImage($remotePath);
		
		var_dump($data);
		
	}
}
